package com.code.question5.client;

import com.alibaba.fastjson.JSON;
import com.code.question5.impl.CustomerServiceImpl;
import com.code.question5.model.User;

import java.io.*;
import java.net.Socket;

/**
 * 客户端
 */
public class CustomerClient {
    public static void main(String[] args) {
        //初始化客户端服务
        CustomerServiceImpl csi = null;
        try {
            csi = new CustomerServiceImpl();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Socket s = null;
        PrintStream ps = null;
        try {
            //用户登录或注册 首页功能
            User user = null;
            do {
                user = csi.Index();
            } while (user == null);
            //登录或注册成功后连接服务器
            s = new Socket("127.0.0.1", 8888);
            //连接成功后向服务器发送当前登录用户信息
            ps = new PrintStream(s.getOutputStream());
            ps.println(JSON.toJSONString(user));
            boolean online = true;
            //进入内容页，功能选项。可进行聊天或者发送文件
            while (online) {
                csi.Menu();
                String menu = new BufferedReader(new InputStreamReader(System.in)).readLine();
                switch (menu) {
                    case "1":
                        csi.Talk(s, user);
                        break;
                    case "2":
                        csi.Upload(s, user);
                        break;
                    default:
                        online = false;
                        csi.Logout(user);
                        System.out.println("欢迎下次光临");
                        break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (null != ps) {
                ps.close();
            }
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
